<template>
  <!-- 数据维护 -->
  <el-container>
      <!-- 页面主体区域 -->
      <el-main class="vs-workbench-main-scoped">
        <el-card shadow="never" class="content-card-scoped">
          <!-- 编辑条件区域 -->
          <el-row :gutter="24">
            <el-col :span="6">
              <span class="title_bottom_border">
                {{ chooseNode.name || '&nbsp;' }}
              </span>
            </el-col>
            <el-col :span="18">
              <el-form :inline="true" style="text-align: right;">
                <el-form-item>
                  <el-input placeholder="请输入名称" v-model="name" class="input-with-select">
                    <el-button slot="append" icon="el-icon-search" @click="querySearch"></el-button>
                  </el-input>
                </el-form-item>
                <el-form-item>
                  <el-button
                      type="primary"
                      @click="addRow()"
                      :disabled="tableHead.length==0"
                      style="margin-left:10px"
                  >新增
                  </el-button
                  >
                </el-form-item>
                <el-form-item>
                  <el-button
                      type="primary"
                      @click="exportFile"
                      :disabled="tableHead.length==0"
                      style="margin-left:10px"
                  >导出
                  </el-button
                  >
                </el-form-item>
                <el-form-item>
                  <el-button size="medium" type="primary" :disabled="tableHead.length==0" @click="moreDelete('all')">
                    全部删除
                  </el-button>
                </el-form-item>
                <el-form-item>
                  <el-button
                      :disabled="multipleSelection.length ==0 || tableHead.length==0"
                      type="primary"
                      @click="moreDelete()"
                      style="margin-left:10px"
                  >批量删除
                  </el-button
                  >
                </el-form-item>
                <!-- <el-form-item>
                  <el-button size="medium" type="primary" @click="calculateTVD()">计算垂深</el-button>
                </el-form-item> -->
              </el-form>
            </el-col>
          </el-row>
          <!-- 表格区域 -->
          <el-row :gutter="24">
            <el-col :span="6" style="height: calc(100vh - 265px);overflow-y: auto;">
              <!--树型控件区域 -->
              <div>
                <el-tree
                    class="leftTree"
                    ref="leftTree"
                    :data="leftTree"
                    :current-node-key="chooseNode.id"
                    node-key="id"
                    :highlight-current="true"
                    @node-click="handleNodeClick"
                    default-expand-all>
                  <div class="custom-tree-node" slot-scope="{ node, data }">
                    <div>{{ data.name }}</div>
                  </div>
                </el-tree>
              </div>
            </el-col>
            <el-col :span="18">
              <el-row class="tableArea">
                <el-table
                    :data="tableData"
                    tooltip-effect="dark"
                    :style="tableStyle"
                    :height="tableHei"
                    :max-height="tableHei"
                    fit
                    border
                    stripe
                    v-loading="loading"
                    element-loading-text="loading"
                    element-loading-spinner="el-icon-loading"
                    element-loading-background="rgba(0, 0, 0, 0.8)"
                    @selection-change="handleSelectionChange"
                    ref="tableArea"
                >
                  <el-table-column type="selection" fixed="left"></el-table-column>
                  <el-table-column
                      type="index"
                      :index="indexMethod"
                      label="序号"
                      align="center"
                      width="50"
                  ></el-table-column>
                  <el-table-column v-for="item in tableHead.filter(n=>n.code !='XMID')" :key="item.id"
                                   :prop="item.code"
                                   :label="item.name"
                                   header-align="center"
                                   align="center"
                                   show-overflow-tooltip
                                   min-width="200px"
                  >
                    <template slot-scope="scope">
                      {{formatterData(scope.row[item.code],item.type)}}
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center" min-width="120" fixed="right">
                    <template slot-scope="scope">
                      <el-button
                          type="text"
                          size="small"
                          @click="editRow(scope.row)"
                      >
                        编辑
                      </el-button>
                      <el-button
                          type="text"
                          size="small"
                          @click="deleteOne(scope.row.id)"
                      >
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-row>
              <el-row>
                <!--分页-->
                <div class="pagination" @click="pageClick($event)">
                  <el-pagination
                      @size-change="handleSizeChange"
                      @current-change="handleCurrentChange"
                      :current-page="currentPage"
                      :page-sizes="[10, 20, 30, 40]"
                      :page-size="pageSize"
                      layout="sizes,total,prev,pager,next"
                      :total="total"
                  ></el-pagination>
                </div>
              </el-row>
            </el-col>
          </el-row>
          <el-dialog
              title="数据维护"
              :visible.sync="fixFlag"
              v-if="fixFlag"
              width="70%"
              :close-on-click-modal="false"
              @close="handleClose">
            <div>
              <div>
                <el-row :gutter="24">
                  <el-form
                      class="formData"
                      :model="formData"
                      :inline="false"
                      label-width="150px"
                      :rules="formRules"
                      ref="rowData"
                      size="large">
                    <el-col :span="8" v-for="(item,index) in tableHead" :key="index">
                      <el-form-item :prop="item.code">
                        <div slot="label">
                          <text-over-tooltip :refName="'title_deal_'+item.code" :content="(item.isNull=='NO'?'<span style=\'color:red;margin-right: 4px;\'>*</span>':'')+item.name+'：'"></text-over-tooltip>
                        </div>
                        <el-input v-model="formData[item.code]" :placeholder="'请输入'+item.name" maxlength="999999999999"
                                  :disabled="item.primaryKey=='PRI' && formData.id != ''" type="number"
                                  v-if="item.type=='decimal'">
                        </el-input>
                        <el-date-picker
                            :disabled="item.primaryKey=='PRI' && formData.id != ''"
                            v-else-if="item.type=='date' || item.type=='datetime'"
                            v-model="formData[item.code]"
                            style="width: 100%;"
                            type="date"
                            format="yyyy-MM-dd"
                            value-format="yyyy-MM-dd"
                            :placeholder="'请选择'+item.name">
                        </el-date-picker>
                        <el-input v-model="formData[item.code]" :placeholder="'请输入'+item.name" maxlength="200"
                                  :disabled="item.primaryKey=='PRI' && formData.id != ''" v-else>
                        </el-input>
                      </el-form-item>
                    </el-col>
                  </el-form>
                </el-row>
              </div>
              <div slot="footer" class="dialog-footer">
                <el-button size="middle" @click="handleClose">取 消</el-button>
                <el-button size="middle" type="primary" @click="saveRow">确 定</el-button>
              </div>
            </div>
          </el-dialog>
        </el-card>
      </el-main>
  </el-container>
</template>
<script>
import cascaderTree from "@/lib/cascaderTree";
import TextOverTooltip from "./dialog/TextOverTooltip.vue";
import {formatterDateBySlash,deepClone} from "@/lib/comFun.js";
import {getFileType,selectTableHead,getMaintenanceList,deleteMaintenanceRow,saveRow,downloadPhone} from "@/api/datamanage/dataMaintenance";
// import {Loading} from "element-ui";

export default {
  components: {TextOverTooltip},
  //名称
  name: "dataMaintenance",
  data() {
    return {
      userInfo: JSON.parse(sessionStorage.getItem("userInfo")),
      formData: {
        'STEP_ID': '',
        'NODE_ID': ''
      },
      tableHead: [],
      leftTree: [],
      name: "",
      chooseNode: {
        id: "",
        pid: "",
        code: "",
        name: "",
        filePath: "",
        floorId: ""
      },
      tableData: [],
      tableStyle: "width:100%;",
      pageSize: 10,
      currentPage: 1,
      total: 0,
      loading: false,
      fixFlag: false,
      multipleSelection: [],
      formRules: {},
      project: {
          projectId: "4FFB57F533FE41CFA3C679636BDC341D",
          projectName: "测试",
          stepId: "C2DFFF737805494ABE3B27347ADC6DC7",
          projectBasin: "盆地1",
          projectBasinName: null,
          projectStructure: "构造单元1",
          projectStructureName: "构造单元1",
          oidField: "油气田1",
          oidFieldTm: "field1",
          oidFieldName: "油气田1",
          stepName: "发现评估,早期评估",
          nodeEvaluateTime: "2023/06/23",
          nodeList: [
              {
                  id: "PROS_EARLY",
                  name: "发现评估"
              },
              {
                  id: "PROS_DISCOVERY",
                  name: "早期评估"
              }
          ]
      },

      tableHei:0
    };
  },
  created(){
    this.tableHei = this.getClientHeight() - 310;
  },
  mounted() {
    this.getFileType();
  },
  methods: {
    /*格式化数据*/
    formatterData(data,type){
      if(type == "date" || type == "datetime"){
        return formatterDateBySlash(data,"/")
      }
      return data;
    },
    getClientHeight() {
      var clientHeight = 0;
      // if (document.body.clientHeight && document.documentElement.clientHeight) {
      //   var clientHeight = (document.body.clientHeight < document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight;
      // } else {
      //   var clientHeight = (document.body.clientHeight > document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight;
      // }
      return clientHeight;
    },
    /*获取全部文件类型*/
    getFileType() {
      let params = {};
      getFileType(params).then((data) => {
          /*if (!data.code == 200) {
              this.$message({
                message: "查询图件分类失败！",
                type: "warning"
              });
              return;
            } else {*/
              let treeData = deepClone(data)
              //let findIndex = treeData.findIndex(n => n.id == 'd31b9ab1-e07d-0ad2-23fc-3d0e1e9e30c8');
              //treeData.splice(findIndex, 1)
              this.leftTree = new cascaderTree(treeData, "id", "pid").init();
              const firstNode = data.filter(n => n.code != '') || [];
              if (firstNode.length > 0) {
                this.handleNodeClick(firstNode[0]);
              }
          //}
      })
    },
    /*点击树节点*/
    handleNodeClick(data, node) {
      if (data.code != '') {
        this.chooseNode = data;
        this.currentPage = 1;
        this.queryAll()
      }
    },
    queryAll() {
      let tableData1 = this.queryTableHead();
      let tableData2 = this.queryTableData();
      this.tableData = [];
      this.tableHead = [];
      Promise.all([tableData1, tableData2]).then((res) => {
        this.tableHead = res[0];
        this.$nextTick(() => {
          this.$refs.tableArea.doLayout(); //解决表格错位
        });
      }).catch(res => {
        this.$message({
          showClose: true,
          type: "warning",
          message: "数据加载失败！"
        });
      })
    },
    //分页多行变少行，点击翻页不刷新问题
    pageClick(e) {
      if (!this.tableData.length) {
        return false;
      }
    },
    /**
     * 序号
     */
    indexMethod(index) {
      return index + this.pageSize * (this.currentPage - 1) + 1;
    },
    /**
     * 页面数据条数改变时
     */
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.queryTableData();
    },
    /**
     * 翻页
     */
    handleCurrentChange(val) {
      this.currentPage = val;
      this.queryTableData();
    },
    /*名称模糊查询*/
    querySearch() {
      this.currentPage = 1;
      this.queryTableData();
    },
    /*多选*/
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    /*批量删除*/
    moreDelete(type) {
      const ids = this.multipleSelection.map(n => n.id).join(",");
      this.deleteOne(ids, type);
    },
    /*删除单条*/
    deleteOne(id, type) {
      let that = this;
      this.$confirm("删除所选数据\n" + "请确认继续吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
          .then(() => {
            let params = {
              ids: id,
              tableCode: that.chooseNode.code
            }
            deleteMaintenanceRow(params).then((data) => {
                if (!data.code == 200) {
                  this.$message({
                    message: "删除失败",
                    type: "warning"
                  });
                  return;
                } else {
                  this.$message({
                    message: "删除成功",
                    type: "success",
                  });
                  this.currentPage = 1;
                  this.queryTableData();
                }

            })


            // axios({
            //   method: "delete",
            //   url: AJAXPathConfig.dataManage.getBasePath() + '/dataLoad/deleteRow',
            //   params: {
            //     ids: id,
            //     tableCode: that.chooseNode.code,
            //     projectId: that.project.projectId
            //   },
            //   success: data => {
            //     if (!data.meta.success || data.data === "") {
            //       this.$message({
            //         message: data.mate.message,
            //         type: "warning"
            //       });
            //       return;
            //     } else {
            //       this.$message({
            //         message: "删除成功",
            //         type: "success",
            //       });
            //       this.currentPage = 1;
            //       this.queryTableData();
            //     }
            //   },
            //   error: e => {
            //     this.$message({
            //       showClose: true,
            //       type: "warning",
            //       message: "删除数据失败！"
            //     });
            //   }
            // });



          })
          .catch(() => {
          });
    },
    /**
     * 计算相关表的垂深并更新
     *
     **/
    // calculateTVD() {
    //   let that = this;
    //   this.$confirm("计算垂深并更新的相关表比较多，需要耐心等待\n" + "请确认继续吗？", "提示", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消",
    //     type: "warning",
    //   })
    //       .then(() => {
    //         let loading = Loading.service({
    //           fullscreen: true,
    //           text: "计算并更新垂深中，请耐心等候",
    //           spinner: "el-icon-loading",
    //           background: "rgba(0, 0, 0, 0.7)"
    //         });
    //
    //         let params = {
    //           projectId: that.project.projectId
    //         }
    //         relatedTvd.then((data) => {
    //             if (!data.meta.success || data.data === "") {
    //               this.$message({
    //                 message: data.mate.message,
    //                 type: "warning"
    //               });
    //               loading
    //               return;
    //             } else {
    //               this.$message({
    //                 message: "计算并更新垂深成功！",
    //                 type: "success",
    //               });
    //               this.currentPage = 1;
    //               this.queryTableData();
    //             }
    //         })
    //         axios({
    //           method: "post",
    //           url: AJAXPathConfig.dataManage.getBasePath() + '/calculate/related/tvd',
    //           params: {
    //             projectId: that.project.projectId
    //           },
    //           success: data => {
    //             if (!data.meta.success || data.data === "") {
    //               this.$message({
    //                 message: data.mate.message,
    //                 type: "warning"
    //               });
    //               loading
    //               return;
    //             } else {
    //               this.$message({
    //                 message: "计算并更新垂深成功！",
    //                 type: "success",
    //               });
    //               this.currentPage = 1;
    //               this.queryTableData();
    //             }
    //           },
    //           error: e => {
    //             this.$message({
    //               showClose: true,
    //               type: "warning",
    //               message: "计算并更新垂深数据失败！"
    //             });
    //           }
    //         }).finally(() => {
    //           loading.close()
    //         });
    //
    //
    //
    //       })
    // },
    /*编辑*/
    editRow(row) {
      this.setRule();
      this.formData = deepClone(row);
      this.fixFlag = true;
    },
    /*新增*/
    addRow() {
      this.setRule();
      this.tableHead.forEach(item => {
        this.$set(this.formData, item.code, "");
      })
      this.$set(this.formData, "id", "");
      this.$set(this.formData, "STEP_ID", this.project.stepId);
      this.$set(this.formData, "NODE_ID", this.project.nodeList.map(n => n.id).join(','));
      this.fixFlag = true;
    },
    setRule() {
      const list = this.tableHead.filter(n => n.isNull == 'NO');
      list.forEach(item => {
        this.$set(this.formRules, item.code, [{required: true, message: "请输入" + item.name, trigger: "blur"}])
      })
    },
    handleClose() {
      this.formData = {};
      this.formRules = {}
      this.fixFlag = false;
    },
    saveRow() {
      this.$refs.rowData.validate((valid) => {
        if (valid) {
          this.doSave();
        } else {
          return;
        }
      })
    },
    doSave() {
      const loading = this.$loading({
        lock: true,
        text: "数据加载中，请稍后",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      saveRow(this.setParams()).then((data) => {
          if (!data.code == 200) {
            this.$message({
              showClose: true,
              type: "warning",
              message: "数据维护失败！"
            });
          } else {
            this.$message({
              showClose: true,
              type: "success",
              message: "数据维护成功！"
            });
            this.handleClose();
            this.queryTableData();
          }

        loading.close();
      });
    },
    setParams() {
      // let _this = this;
      let stepId = "";
      // if (this.formData['STEP_ID'].indexOf(this.project.stepId) > -1) {
      //   stepId = this.formData['STEP_ID'];
      // } else {
      //   stepId = this.formData['STEP_ID'] + ',' + this.project.stepId;
      // }
      let nodeId = "";
      // if (this.formData['NODE_ID'].indexOf(this.project.nodeList.map(n => n.id).join(",")) > -1) {
      //   nodeId = this.formData['NODE_ID'];
      // } else {
      //   nodeId = this.formData['NODE_ID'] + ',' + this.project.nodeList.map(n => n.id).join(",");
      // }
      let param = {
        id: this.formData["id"] || "",
        data: this.formData,
        tableName: this.chooseNode.code,
        stepId: stepId,
        projectId: this.project.projectId,
        userCode: "",
        nodeId: nodeId
      };
      return param;
    },
    exportFile() {
      // const projectId = this.project.projectId;
      const params = {
        projectId: this.project.projectId,
        tableName: this.chooseNode.name,
        tableCode: this.chooseNode.code,
      }
      //window.open(downloadPhone(params), '_blank');
      this.download('/assessDataMessage/dataManage/dataLoad/downloadPhone',
        params,this.chooseNode.name + '.csv');
      return;
    },
    /**
     * @Author: ddhhh
     * @Params: {{Params}}
     * @Description: 获取数据
     */
    queryTableData() {
      this.loading = true;
      return new Promise((resolve, reject) => {
        const searchList = this.tableHead.filter(n => n.isSearch == '1').map(n => n.code);
        let params = {
            projectId: this.project.projectId,
            nodeId: "",
            page: this.currentPage,
            rows: this.pageSize,
            well_no: this.name.trim(),
            tableName: this.chooseNode.code,
            searchList: searchList.length > 0 ? searchList.join(',') : ''
        }
        getMaintenanceList(params).then((data) => {
            if (!data.code == 200) {
              reject('数据加载失败');
            } else {
              this.tableData = data.rows;
              this.total = data.total;
              resolve();
            }
            this.loading = false
        });
      })
    },
    /**
     * @Author: ddhhh
     * @Params: {{Params}}
     * @Description: 数据表头
     */
    queryTableHead() {
      return new Promise((resolve, reject) => {
        let params = {
          tableCode: this.chooseNode.code
        }
        selectTableHead(params).then((data) => {
            // if (!data.code == 200) {
            //   reject('数据加载失败');
            // } else {
              resolve(data);
            //}
        });

      })
    },
  },
};
</script>
<style scoped>
.content-card-scoped >>> .el-card__body {
  padding: 10px 20px;
}

.leftTree >>> .is-current .el-tree-node__content {
  background-color: #deeaf7;
}

.leftTree >>> .is-current .el-tree-node__children .el-tree-node__content {
  background-color: #ffffff;
}

.title_bottom_border {
  padding: 0px 10px 5px 10px;
  min-width: 100px;
  border-bottom: 4px solid rgb(30, 148, 208);
}

.tableArea >>> .el-table__body-wrapper {
  height: calc(100% - 40px) !important;
}

.moreTextShow {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.dialog-footer {
  text-align: center;
}

.formData >>> .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:before {
  display: none;
}
</style>
